<?php


class DingTalk_Service {
    const OAPI_HOST = "https://oapi.dingtalk.com";


    public function get($path, $params) {
        $cache = DI()->cache->get("DingTalk:" . $this->config['CORPID'] . str_replace("/", ":", $path));
        if (!$cache || $path != "/createSignature") {
            $url = self::joinParams($path, $params);
            $curl = new PhalApi_CUrl();
            $response = $curl->get($url, 3000, ['Content-Type:application/json']);
            $response = @json_decode($response, true);
            self::check($response);
            DI()->cache->set("DingTalk:" . $this->config['CORPID'] . str_replace("/", ":", $path), $response, $path == "/gettoken" ? (60 * 60 * 2 - 100) : 60);
            $cache = $response;
        }

        return $cache;
    }


    public function post($path, $params, $data) {
        $url = self::joinParams($path, $params);
        $curl = new PhalApi_CUrl();
        $response = $curl->post($url, $data, 3000, ['Content-Type:application/json']);
        $response = @json_decode($response, true);
        self::check($response);
        return $response;
    }


    private static function joinParams($path, $params) {
        $url = self::OAPI_HOST . $path;
        if (count($params) > 0) {
            $url = $url . "?";
            foreach ($params as $key => $value) {
                $url = $url . $key . "=" . $value . "&";
            }
            $length = strlen($url);
            if ($url[$length - 1] == '&') {
                $url = substr($url, 0, $length - 1);
            }
        }
        return $url;
    }

    public function getCorpAccessToken() {
        $corpAccessToken = DI()->cache->get("corp_access_token:" . $this->config['CORPID']);
        if (!$corpAccessToken) {
            $response = $this->get("/gettoken",
                [
                    "corpid"     => $this->config['CORPID'],
                    "corpsecret" => $this->config['SECRET'],
                ]);
            $corpAccessToken = $response['access_token'];
            DI()->cache->set("corp_access_token:" . $this->config['CORPID'], $corpAccessToken, 60 * 60 * 2 - 100);
        }
        return $corpAccessToken;
    }

    public function getJsapiTicket() {
        $corpJsapi_ticket = DI()->cache->get("corp_jsapi_ticket:" . $this->config['CORPID']);
        if (!$corpJsapi_ticket) {
            $response = $this->get("/get_jsapi_ticket",
                [
                    "access_token" => $this->getCorpAccessToken(),
                    "type"         => "jsapi"
                ]
            );
            $corpJsapi_ticket = $response['ticket'];
            DI()->cache->set("corp_access_token:" . $this->config['CORPID'], $corpJsapi_ticket, 7000);
        }

        return $corpJsapi_ticket;
    }

    public function tmp_auth_code($code) {
        $response = $this->post("/sns/get_persistent_code",
            [
                "access_token"  => $this->getCorpAccessToken(),
                "tmp_auth_code" => $code,
            ], []);
        DI()->cache->set("user_persistent_code:" . $response['openid'], $response, 60 * 60 * 2 - 100);

        return $response;
    }

    /**
     * 获取js分享参数
     * @param $url
     * @return signature string 签名
     * @return jsapi_ticket string
     * @return noncestr string
     * @return timestamp string
     * @return url string
     * @return errcode string
     */
    public function createSignature($url) {

//        return $this->get("/createSignature", [
//            "access_token" => $this->getCorpAccessToken(),
//            "noncestr"     => helper_lite::createRandStr(8),
//            "timestamp"    => time(),
//            "url"          => $url,
//            "jsapi_ticket" => $this->getJsapiTicket()
//        ]);

        $nonceStr = DI()->helper->createRandStr(8);
        $timeStamp = time();

        $signature= sha1('jsapi_ticket=' . $this->getJsapiTicket() .
            '&noncestr=' . $nonceStr .
            '&timestamp=' . $timeStamp .
            '&url=' . $url);
        return [
            'url'       => $url,
            'nonceStr'  => $nonceStr,
            'agentId'   => 15724441,
            'timeStamp' => $timeStamp,
            'corpId'    => $this->config['CORPID'],
            'signature' => $signature
        ];
    }


    static function check($res) {
        if ($res['errcode'] != 0) {
            DI()->logger->log("error", T("dingtalk response fail"), json_encode($res));
            throw new PhalApi_Exception($res['errmsg'], $res['errcode']);
        }
    }


}